-- UIHeroInfo
-- Create by chengb Jan/5/2015
-- 英雄信息界面

require "game/ui/form/comment/UIComment"

-- UIHeroInfo继承自Layer
UIHeroInfo = class("UIHeroInfo", function()
    return cc.Layer:create();
end);

function UIHeroInfo.create(info)
    return UIHeroInfo.new(info);
end

-- 构造函数
function UIHeroInfo:ctor(info)
    -- 初始化
    self:setName("UIHeroInfo");
    local node = cc.CSLoader:createNode("layout/hero/HeroInfo.csb");
    self:addChild(node);
    self.node = node;
    self.classId = info.classId;
    self.isActive = info.isActive;

    -- 需要显示在头部菜单上面
    self:setLocalZOrder(UIMgr.BONUS_NOTIFY_ZORDER + 1);

    -- 注册点击事件
    self:registerTouchEvent();

    -- 注册事件回调
    self:registerEventCallback();

    -- 重绘
    self:redraw();

    -- 适配
    self:resize();
end

-- 注册事件回调
function UIHeroInfo:registerEventCallback()
    -- 关注评论数量更新
    EventMgr.register("UIHeroInfo", event.UPDATE_COMMENT_COUNT, function(para)
        if para["commentType"] == "pet_" .. tostring(self.classId) then
            self:checkCommentCount();
        end
    end);

    -- 注册英雄穿上时装的回调
    EventMgr.register("UIHeroInfo", event.EQUIP, function(args)
        local type = EquipM.query(args, "type");
        if type == EQUIP_TYPE_COSTUME then
            local hero = PetM.getMyPet(self.classId);
            local id = EquipM.getCostumeEquiped(hero);
            if id ~= 0 then
                local msg = string.format(getLocStr("change_costume"), ItemM.query(id, "name"));
                alert(msg);
            end

            self:initPanel(true);
        end
    end);

    -- 注册英雄穿上时装的回调
    EventMgr.register("UIHeroInfo", event.UNEQUIP, function(args)
        local type = args.type;
        if type == EQUIP_TYPE_COSTUME then
            self:initPanel(true);
        end
    end);

    -- 关注购买时装结果
    EventMgr.register("UIHeroInfo", event.BUY_COSTUME, function(para)
        printTable(para, "para");
        if para.ret == 0 then
            local msg = string.format(getLocStr("recharge_ok_text"), ItemM.query(para.item_id, "name"));
            confirm2(CONFIRM_TYPE_OK, getLocStr("system_prompt"), msg);
            local hero = PetM.getMyPet(self.classId);
            self:redraw();
            UIMgr.getCurrentScene():removeFormByName("UIBuyCostume");
        else
            alert(getLocStr("market_buy_fail"));
        end
    end);

    -- 关注兑换活动商品的事件
    EventMgr.register("UIHeroInfo", event.ACTIVITY_EXCHANGE, function(args)
        local goodsId   = args.goodsId;
        local num       = args.num;
        local bonus     = args.bonus;

        self:whenExchange(goodsId, num, bonus);
    end);

    self:registerScriptHandler(function(ev)
        if ev == "enter" then
            -- 播放界面音效
            AudioM.playFx("slime_explain");
        elseif ev == "exit" then
            EventMgr.removeAll("UIHeroInfo");
            cclog("UIHeroInfo 界面析构清理");
        end
    end);
end

-- 关闭购买商品的消息
function UIHeroInfo:whenExchange(goodsIndex, num, bonus)
    -- 刷新界面
    self:redraw();
    UIMgr.getCurrentScene():removeFormByName("UIBuyCostume");

    -- 提示玩家兑换了商品
    local function delay()
        if bonus[1] == 1 then
            name = ItemM.query(bonus[2], "name");
        elseif bonus[1] == ROBOT then
            name = SkyRobotM.query(bonus[2], "name");
        elseif bonus[1] == 2 then
            name = FieldsM.query(bonus[2], "name");
        else
            name = SkyShipSkillM.query(bonus[2], "name");
        end

        count = num * bonus[3];

        local msg = string.format(getLocStr("exchange_tip"), name, count);

        alert(msg);
    end

    performWithDelay(self, delay, 0.1);
end

-- 注册点击事件
function UIHeroInfo:registerTouchEvent()
    -- 注册返回按钮点击事件
    local node = self.node;
    local btnBack = findChildByName(node, "BT/btn_back");
    local function onBackClick(sender, eventType)
        if eventType == ccui.TouchEventType.ended then
            -- 关闭当前界面
            AudioM.playFx("button_return");
            UIMgr.getCurrentScene():removeFormByName("UIHeroInfo");
        end
    end
    AddBackEventHandler(self, btnBack, onBackClick);
    TextStyleM.setTextStyle(btnBack, TextStyleM.TEXT_SIZE_MIDDLE, TextStyleM.TEXT_COLOR_BROWN_YELLOW, true);
    btnBack:setTitleText(getLocStr("btn_text_ok"));

    if self.isBlankClose then
        -- 注册任意地方点击返回事件
        local btnBgBack = findChildByName(self.node, "bg/bgImg");
        local function onBgBackClick(sender, eventType)
            if eventType == ccui.TouchEventType.ended then
                -- 关闭当前界面
                AudioM.playFx("button_return");
                UIMgr.getCurrentScene():removeFormByName("UIHeroInfo");
            end
        end
        btnBgBack:addTouchEventListener(onBgBackClick);
    end

    -- 评论界面参数
    local heroConfig = PetM.query(self.classId);
    local data = {
        ["title"] = PetM.query(self.classId, "name"),
        ["type"] = "pet_" .. tostring(self.classId),
    }

    local btnComment =  findChildByName(node, "BT/btn_comment");
    local function onCommentClick(sender, eventType)
        if eventType ==  ccui.TouchEventType.ended then
            -- 打开评论界面
            AudioM.playFx("button_click");
            UIMgr.getCurrentScene():removeFormByName("UIComment");
            local uiComment = UIComment.create(data);
            UIMgr.getCurrentScene():addForm(uiComment);
        end
    end
    btnComment:addTouchEventListener(onCommentClick);
    TextStyleM.setTextStyle(btnComment, TextStyleM.TEXT_SIZE_MIDDLE, TextStyleM.TEXT_COLOR_BROWN_YELLOW, true);
    btnComment:setTitleText(getLocStr("btn_text_new_comment"));

    -- 获取评论数量
    Operation.cmd_get_comment_counts(data.type);
end

-- 适配
function UIHeroInfo:resize()
    local node = self.node;

    -- bg居中显示并充满整个屏幕
    AlignM.fitToScreen(node, "bg");

    -- CT居中并缩放至合适大小
    AlignM.alignToCenter(node, "CT");

    -- BT置于底部并缩放至合适大小
    AlignM.alignToBottomCenter(node, "BT");
end

-- 重绘
function UIHeroInfo:redraw()
    local CT = self.node:getChildByName("CT");

    -- 获取当前出战的英雄
    local pet = ME.user:getActivePet();
    if pet.classId == self.classId then
        self.isBlankClose = true;
    end

    -- 获取英雄对象
    local hero = PetM.getMyPet(self.classId);

    -- 显示英雄名字
    local heroNameLabel = findChildByName(CT, "hero_name");
    local heroConfig = PetM.query(self.classId);
    TextStyleM.setTextStyle(heroNameLabel, TextStyleM.TEXT_SIZE_MIDDLE, TextStyleM.TEXT_COLOR_DARK_RED, false, kerning);
    heroNameLabel:setString(PetM.query(self.classId, "name"));

    -- 英雄简介
    local heroBriefLabel = findChildByName(CT, "hero_brief");
    TextStyleM.setTextStyle(heroBriefLabel, TextStyleM.TEXT_SIZE_SMALL, TextStyleM.TEXT_COLOR_DARK_BROWN);
    heroBriefLabel = applyString(heroBriefLabel, heroConfig["desc"]);

    local campId = CampM.getPetCamp(self.classId);
    -- 冈布奥阵营简介
    local campNameLabel = findChildByName(CT, "camp_name");
    local campName = CampM.query(campId, "name");
    TextStyleM.setTextStyle(campNameLabel, TextStyleM.TEXT_SIZE_SMALL, TextStyleM.TEXT_COLOR_DARK_RED);

    local campDesc = string.format(getLocStr("pets_camp_desc"), campName);
    campNameLabel:setString(campDesc);

    -- 绘制时装容器
    self:initPanel();

    -- 检查数量
    self:checkCommentCount();

    local costumePanel = findChildByName(CT, "costume_panel");
    local maskTop = findChildByName(self.node, "CT/mask_top");
    local maskBottom = findChildByName(self.node, "CT/mask_bottom");
    if ServerStatusM.query(MODULE_SWITCH_OPEN_COSTUME) ~= 1 or not FeatureItemM.isFeatureOpen("costume") then
        costumePanel:setVisible(false);
        maskTop:setVisible(false);
        maskBottom:setVisible(false);
    end

    local bottomMargin = 30;
    if ServerStatusM.query(MODULE_SWITCH_OPEN_COSTUME) ~= 1 or not FeatureItemM.isFeatureOpen("costume") then
        bottomMargin = 70;
    end

    -- 自适应所有组件
    local bg = findChildByName(self.node, "CT/bg");
    AlignM.adaptLayout(bg, AlignM.BG_SIZE_NORMAL,
        { heroNameLabel, heroBriefLabel, campNameLabel, costumePanel},
        { AlignM.DEFAULT_GAP, AlignM.DEFAULT_GAP, AlignM.DEFAULT_GAP },
        nil, bottomMargin);

    local finalHeight = costumePanel:getContentSize().height;
    local scaleY = bg:getScaleY();
    maskTop:setScaleY(scaleY);
    maskTop:setPositionY(costumePanel:getPositionY() + maskTop:getContentSize().height/2 + 7);

    maskBottom:setScaleY(scaleY * 1);
    local bgY = bg:getPositionY() - AlignM.BG_SIZE_NORMAL.height * scaleY / 2;
    -- maskBottom:setPositionY(bgY + 18 * scaleY*1.2 + 25);
    maskBottom:setPositionY(costumePanel:getPositionY() -  finalHeight);
end

-- 初始化panel
function UIHeroInfo:initPanel(playEffect)
    local CT = self.node:getChildByName("CT");

    -- 获取当前出战的英雄
    local pet = ME.user:getActivePet();

    local costumePanel = findChildByName(CT, "costume_panel");
    costumePanel:removeAllChildren();

    -- 获取时装数量
    local costumeList = table.deepcopy(EquipM.getPetCostumeList(self.classId));
    if table.indexOf(costumeList, 0) == -1 then
        table.insert(costumeList, 1, 0);
    end
    local costumeNum = #costumeList;
    if costumeNum == 0 then
        costumePanel:setVisible(false);
    else
        if costumeNum == 1 then
            costumePanel:setBounceEnabled(false);
        else
            costumePanel:setBounceEnabled(true);
        end

        -- 初始化时装信息
        local itemHeight  = 80;
        local topGap      = 15;
        local panelWidth  = costumePanel:getContentSize().width;
        local totalHeight = costumeNum * (itemHeight + topGap);

        local startHeight = 80 / 2;
        if totalHeight < costumePanel:getContentSize().height then
            startHeight = costumePanel:getContentSize().height - totalHeight + startHeight;
        end

        costumePanel:setInnerContainerSize(cc.size(costumePanel:getInnerContainerSize().width,
            math.max(totalHeight, costumePanel:getContentSize().height)));

        for i, id in pairs(costumeList) do
            local itemNode = cc.CSLoader:createNode("layout/hero/HeroCostumeItem.csb");

            local posX, posY;
            posX = 247;
            posY = startHeight + (costumeNum - i) * (itemHeight + topGap);

            itemNode:setPosition(posX, posY);
            costumePanel:addChild(itemNode);

            self:initPanelItem(id, itemNode, playEffect);
        end
    end
end

-- 初始化表项
function UIHeroInfo:initPanelItem(id, itemNode, playEffect)
    local costumeBg = findChildByName(itemNode, "bg");
    local iconImg   = findChildByName(itemNode, "icon");
    local nameLabel = findChildByName(itemNode, "name");
    local propLabel = findChildByName(itemNode, "prop");
    local operateIcon = findChildByName(itemNode, "op_icon");

    local icon, name, propDesc;
    if id == 0 then
        icon = PetM.getDefaultIcon(self.classId);
        name = string.format(getLocStr("default_costume_name"), PetM.query(self.classId, "short_name"));
        propDesc = getLocStr("desc_no_effect");
    else
        local modelId = EquipM.queryPetModelID(id);
        icon = PetM.queryModel(modelId, "icon");
        name = ItemM.query(id, "name");
        propDesc = extractString(ItemM.query(id, "detail"));
    end

    -- 时装模型图标
    iconImg:loadTexture(getHeroIconPath(icon));
    iconImg:setScale(0.7);

    -- 时装名称
    TextStyleM.setTextStyle(nameLabel, TextStyleM.TEXT_SIZE_MINI, TextStyleM.TEXT_COLOR_BEIGE, false, kerning, nil, nil, nil, nil, nil, TextStyleM.getTextScale(name, 20));
    nameLabel:setString(name);

    -- 时装作用
    TextStyleM.setTextStyle(propLabel, TextStyleM.TEXT_SIZE_MINI, TextStyleM.TEXT_COLOR_BEIGE, false, kerning, nil, nil, nil, nil, nil, TextStyleM.getTextScale(name, 20));
    propLabel:setString(propDesc);

    -- 默认底色为蓝色
    costumeBg:loadTexture(getTitleBgIconPath("point_blue"));

    -- 是否拥有时装道具
    local hero = PetM.getMyPet(self.classId);
    local hasCostume = EquipM.hasCostume(hero, id);
    -- 是否已经穿戴
    local hasEquiped = EquipM.getCostumeEquiped(hero) == id;

    if id == 0 then
        hasCostume = true;
    end

    operateIcon:setPositionX(200);

    if not hasCostume then
        if EquipM.isGemCostume(id) then
            operateIcon:loadTexture(getSettingIconPath("system", "buy"));
        elseif EquipM.isActivityCostume(id) then
            operateIcon:loadTexture(getSettingIconPath("system", "buy"));
        else
            operateIcon:loadTexture(getSettingIconPath("system", "question"));
        end
    elseif not hasEquiped then
        -- 显示穿上的符号
        operateIcon:loadTexture(getSettingIconPath("system", "open"));

        -- 底图显示红色
        costumeBg:loadTexture(getTitleBgIconPath("point_red"));
    else
        -- 显示穿戴中
        local name = string.format(getLocStr("desc_wearing"), name);
        nameLabel:setString(name);

        -- 隐藏操作图标
        operateIcon:setVisible(false);

        -- 底图显示红色
        costumeBg:loadTexture(getTitleBgIconPath("point_red"));

        -- 播放穿上特效
        if playEffect then
            local function play()
                playCostumeWearEffect(iconImg, icon);
            end
            performWithDelay(self, play, 0.1);
        end
    end

    local function onOpClick(sender, eventType)
        setNormalPressEffect(eventType, operateIcon);
        if eventType == ccui.TouchEventType.ended then
            if not hasCostume then
                if EquipM.isGemCostume(id) then
                    -- 显示购买界面
                    require "game/ui/form/hero/UIBuyCostume";
                    local uiform = UIBuyCostume.create(self.classId, id);
                    UIMgr.getCurrentScene():addForm(uiform);
                elseif EquipM.isActivityCostume(id) then
                    -- 显示兑换界面
                    require "game/ui/form/hero/UIBuyCostume";
                    local uiform = UIBuyCostume.create(self.classId, id, "activity");
                    UIMgr.getCurrentScene():addForm(uiform);
                else
                    -- 显示获取途径
                    local getDesc = EquipM.query(id, "detail");
                    confirm2(CONFIRM_TYPE_OK, name, getDesc);
                end
            elseif not hasEquiped then
                if PetM.isActivePet(self.classId) then
                    AudioM.playFx("slime_gain_failed");
                    alert(getLocStr("gumball_active_tip"));
                    return;
                end

                AudioM.playFx("get_slime");

                if id == 0 then
                    -- 脱下当前的时装
                    Operation.cmd_hero_unequip(hero, EQUIP_TYPE_COSTUME);

                    local msg = string.format(getLocStr("change_costume"), name);
                    alert(msg);
                else
                    -- 穿上当前的时装
                    Operation.cmd_hero_equip(hero, id);
                end
            end
        end
    end
    operateIcon:setTouchEnabled(true);
    operateIcon:addTouchEventListener(onOpClick);
end

-- 检查评论数量
function UIHeroInfo:checkCommentCount()
    -- 评论按钮
    local btnComment = findChildByName(self.node, "BT/btn_comment");
    local commentLabel = findChildByName(btnComment, "comment_label");
    local hintNode = findChildByName(btnComment, "hint");
    local commentType = "pet_" .. tostring(self.classId);
    local count = CommentM.getCommentCount(commentType);

    local kerning = 0;
    if getLang() == "zh" or getLang == "tw" then
        kerning = 4;
    end

    TextStyleM.setTextStyle(commentLabel, TextStyleM.TEXT_SIZE_MIDDLE, TextStyleM.TEXT_COLOR_BROWN_YELLOW, true, kerning, nil, nil, nil, nil, true);
    btnComment:setTitleText("");
    commentLabel:setString(string.format(getLocStr("btn_text_comment_num"), count));
end
